package com.example.tests;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;

public class GroupDataGenerator extends DataGeneratorBase{

	
	public static void main(String[] args) throws IOException {
		if (!checkArguments(args)){
			return;
		}
		
		int amount = Integer.parseInt(args[0]);
		File file = new File(args[1]);
		String format = args[2];
		
		List<GroupData> data = generateRandomGroups(amount);
		if ("csv".equals(format)) {
			saveGroupsToCsvFile(data, file);
		} else if ("xml".equals(format)) {
			saveGroupsToXmlFile(data, file);
		} 
	}

	private static void saveGroupsToXmlFile(List<GroupData> groups, File file) throws IOException {
		XStream xstream = new XStream();
		xstream.alias("group", GroupData.class);
		String xml = xstream.toXML(groups);
		FileWriter writer = new FileWriter(file);
		writer.write(xml);
		writer.close();
	}

	public static List<GroupData> loadGroupsFromXmlFile(File file) throws Exception {
		XStream xstream = new XStream();
		xstream.alias("group", GroupData.class);
		return (List<GroupData>) xstream.fromXML(file);
	}

	
	private static void saveGroupsToCsvFile(List<GroupData> groups, File file) throws IOException {
		FileWriter writer = new FileWriter(file);
		for (GroupData group : groups) {
			writer.write(group.getName() +","+ group.getHeader() +","+group.getFooter()+",!\n");
		}
		writer.close();
	}
	
	public static List<GroupData> loadGroupsFromCsvFile(File file) throws Exception {
		List<GroupData> list = new ArrayList<GroupData>();
		FileReader reader = new FileReader(file);
		BufferedReader bufferedReader = new BufferedReader(reader);
		
		String line = bufferedReader.readLine();
		while (line != null) {
			String[] part = line.split(",");
			GroupData group = new GroupData()
				.withName(part[0])
				.withHeader(part[1])
				.withFooter(part[2]);
			list.add(group);
			line = bufferedReader.readLine();
		}
		
		bufferedReader.close();
		return list;
	}

	public static List<GroupData> generateRandomGroups(int amount) {
		List<GroupData> list = new ArrayList<GroupData>();
		for (int i = 0; i < 5; i++) {
			GroupData group = new GroupData()
					.withName(generateRandomString(30))
					.withHeader(generateRandomString(30))
					.withFooter(generateRandomString(30));
			list.add(group);
		}
		return list;
	}
}
